package ssi.peeno;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import org.bouncycastle.util.encoders.Base64;

import ssi.peeno.managers.ConfigManager;

/**
 * This class generates the private key and the public key of the server,
 * the relative certificate and store it on the KeyStore.
 */
public class ServerKeyGenerator {
	public static void main(String[] args) {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		ConfigManager.log("Starting generation...");
		KeyPairGenerator kpg = null;
		try {
			kpg = KeyPairGenerator.getInstance("RSA", "BC");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		}
		kpg.initialize(1024);
		KeyPair pair = kpg.generateKeyPair();
		FileOutputStream os = null;
		FileOutputStream os1 = null;
		try {
			os = new FileOutputStream("keys/Local.private");
			os1 = new FileOutputStream("keys/Local.public");
			os.write(Base64.encode(pair.getPrivate().getEncoded()));
			os1.write(Base64.encode(pair.getPublic().getEncoded()));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
				os1.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		ConfigManager.log("Finished");
	}
}
